<template>
  <el-dialog
    v-model="visible"
    :title="file?.title || '分享文件'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="knowledge-share-dialog"
  >
    <div v-loading="loading" class="share-container">
      <!-- 已有分享链接 -->
      <div v-if="shareInfo" class="share-info">
        <el-alert
          type="success"
          :closable="false"
          show-icon
          style="margin-bottom: 20px"
        >
          <template #title>
            <span>分享链接已创建</span>
          </template>
        </el-alert>

        <div class="share-url-section">
          <div class="share-url-label">分享链接：</div>
          <div class="share-url-input-group">
            <el-input
              v-model="shareInfo.share_url"
              readonly
              ref="shareUrlInputRef"
            >
              <template #append>
                <el-button @click="handleCopyUrl" :icon="CopyDocument">
                  复制
                </el-button>
              </template>
            </el-input>
          </div>
        </div>

        <div class="share-stats">
          <div class="stat-item">
            <span class="stat-label">访问次数：</span>
            <span class="stat-value">{{ shareInfo.access_count }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">过期时间：</span>
            <span class="stat-value">
              <span v-if="shareInfo.expires_at">{{ formatDate(shareInfo.expires_at) }}</span>
              <span v-else class="never-expires">永不过期</span>
            </span>
          </div>
          <div class="stat-item" v-if="shareInfo.max_access_count">
            <span class="stat-label">最大访问次数：</span>
            <span class="stat-value">{{ shareInfo.max_access_count }}</span>
          </div>
        </div>

        <div class="share-settings">
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="允许下载">
              <el-tag :type="shareInfo.allow_download ? 'success' : 'info'">
                {{ shareInfo.allow_download ? '是' : '否' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="过期时间">
              <el-tag :type="shareInfo.expires_at ? 'info' : 'success'">
                {{ shareInfo.expires_at ? formatDate(shareInfo.expires_at) : '永不过期' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="访问密码">
              <el-tag :type="shareInfo.has_password ? 'warning' : 'info'">
                {{ shareInfo.has_password ? '已设置' : '未设置' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="shareInfo.is_active ? 'success' : 'danger'">
                {{ shareInfo.is_active ? '有效' : '已失效' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="share-actions">
          <el-button type="danger" @click="handleRevoke" :loading="revoking">
            撤销分享
          </el-button>
          <el-button @click="handleUpdate">更新设置</el-button>
        </div>
      </div>

      <!-- 创建分享链接表单 -->
      <el-form
        v-else
        ref="shareFormRef"
        :model="shareForm"
        :rules="shareFormRules"
        label-width="120px"
        class="share-form"
      >
        <el-form-item label="允许下载" prop="allow_download">
          <el-switch v-model="shareForm.allow_download" />
          <span class="form-tip">开启后，访问者可以下载文件</span>
        </el-form-item>

        <el-form-item label="有效期" prop="expires_in_hours">
          <el-select v-model="shareForm.expires_in_hours" placeholder="选择有效期" clearable>
            <el-option label="永不过期" :value="0" />
            <el-option label="1小时" :value="1" />
            <el-option label="6小时" :value="6" />
            <el-option label="24小时" :value="24" />
            <el-option label="7天" :value="168" />
            <el-option label="30天" :value="720" />
          </el-select>
          <span class="form-tip">选择"永不过期"或留空表示链接永久有效</span>
        </el-form-item>

        <el-form-item label="最大访问次数" prop="max_access_count">
          <el-input-number
            v-model="shareForm.max_access_count"
            :min="1"
            :max="10000"
            placeholder="不限制"
            style="width: 100%"
          />
          <span class="form-tip">达到次数后链接将失效</span>
        </el-form-item>

        <el-form-item label="访问密码" prop="password">
          <el-input
            v-model="shareForm.password"
            type="password"
            placeholder="设置密码（可选）"
            show-password
            clearable
          />
          <span class="form-tip">设置密码后，访问者需要输入密码才能查看</span>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          v-if="!shareInfo"
          type="primary"
          @click="handleCreate"
          :loading="creating"
        >
          创建分享链接
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'
import {
  createKnowledgeShare,
  getKnowledgeShare,
  revokeKnowledgeShare,
  type KnowledgeFile,
  type KnowledgeShare,
  type CreateKnowledgeShareParams
} from '@/api/knowledge'
import { ResponseParser } from '@/utils/responseParser'

interface Props {
  modelValue: boolean
  file?: KnowledgeFile
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'updated'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const loading = ref(false)
const creating = ref(false)
const revoking = ref(false)
const shareInfo = ref<KnowledgeShare | null>(null)
const shareFormRef = ref()
const shareUrlInputRef = ref()

const shareForm = reactive<{
  allow_download: boolean
  expires_in_hours: number | undefined
  max_access_count: number | undefined
  password: string | undefined
}>({
  allow_download: true,
  expires_in_hours: 0, // 0 表示永不过期
  max_access_count: undefined,
  password: undefined
})

const shareFormRules = {
  expires_in_hours: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value !== undefined && value !== null && value < 0) {
          callback(new Error('有效期不能为负数'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  max_access_count: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value !== undefined && value !== null && (value < 1 || value > 10000)) {
          callback(new Error('访问次数必须在1-10000之间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal
    if (newVal && props.file) {
      fetchShareInfo()
    }
  }
)

// 监听 visible 变化，同步到 modelValue
watch(visible, (newVal) => {
  if (!newVal) {
    emit('update:modelValue', false)
  }
})

// 获取分享信息
const fetchShareInfo = async () => {
  if (!props.file) return

  try {
    loading.value = true
    const response = await getKnowledgeShare(props.file.id)
    const parsed = ResponseParser.parseResponse<KnowledgeShare | null>(response)
    if (parsed.success) {
      shareInfo.value = parsed.data
    } else {
      shareInfo.value = null
    }
  } catch (error: any) {
    console.error('获取分享信息失败:', error)
    // 如果返回404，说明没有分享链接，这是正常的
    if (error?.response?.status !== 404) {
      ElMessage.error('获取分享信息失败')
    }
    shareInfo.value = null
  } finally {
    loading.value = false
  }
}

// 创建分享链接
const handleCreate = async () => {
  if (!props.file) return

  try {
    await shareFormRef.value?.validate()
    creating.value = true

    const params: CreateKnowledgeShareParams = {
      allow_download: shareForm.allow_download,
      expires_in_hours: shareForm.expires_in_hours === 0 || shareForm.expires_in_hours === undefined || shareForm.expires_in_hours === null 
        ? undefined 
        : shareForm.expires_in_hours,
      max_access_count: shareForm.max_access_count,
      password: shareForm.password || undefined
    }

    const response = await createKnowledgeShare(props.file.id, params)
    const parsed = ResponseParser.parseResponse<KnowledgeShare>(response)
    if (parsed.success && parsed.data) {
      shareInfo.value = parsed.data
      ElMessage.success('创建分享链接成功')
      emit('updated')
    }
  } catch (error: any) {
    console.error('创建分享链接失败:', error)
    ElMessage.error(error?.response?.data?.message || '创建分享链接失败')
  } finally {
    creating.value = false
  }
}

// 更新分享设置
const handleUpdate = () => {
  // 重置表单并显示创建表单
  shareInfo.value = null
  shareForm.allow_download = true
  shareForm.expires_in_hours = 0 // 0 表示永不过期
  shareForm.max_access_count = undefined
  shareForm.password = undefined
}

// 撤销分享
const handleRevoke = async () => {
  if (!props.file) return

  try {
    await ElMessageBox.confirm('确定要撤销此分享链接吗？撤销后链接将无法访问。', '确认撤销', {
      type: 'warning'
    })

    revoking.value = true
    await revokeKnowledgeShare(props.file.id)
    shareInfo.value = null
    ElMessage.success('撤销分享链接成功')
    emit('updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('撤销分享链接失败:', error)
      ElMessage.error('撤销分享链接失败')
    }
  } finally {
    revoking.value = false
  }
}

// 复制分享链接
const handleCopyUrl = async () => {
  if (!shareInfo.value?.share_url) return

  try {
    await navigator.clipboard.writeText(shareInfo.value.share_url)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    // 降级方案：使用传统方法
    const input = shareUrlInputRef.value?.$el?.querySelector('input')
    if (input) {
      input.select()
      document.execCommand('copy')
      ElMessage.success('链接已复制到剪贴板')
    } else {
      ElMessage.error('复制失败，请手动复制')
    }
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  shareInfo.value = null
  // 重置表单
  shareForm.allow_download = true
  shareForm.expires_in_hours = undefined
  shareForm.max_access_count = undefined
  shareForm.password = undefined
}
</script>

<style scoped lang="scss">
.knowledge-share-dialog {
  .share-container {
    min-height: 200px;
  }

  .share-info {
    .share-url-section {
      margin-bottom: 20px;

      .share-url-label {
        margin-bottom: 8px;
        font-weight: 500;
        color: #606266;
      }

      .share-url-input-group {
        :deep(.el-input-group__append) {
          padding: 0;
        }
      }
    }

    .share-stats {
      display: flex;
      gap: 24px;
      margin-bottom: 20px;
      padding: 16px;
      background: #f5f7fa;
      border-radius: 4px;

      .stat-item {
        .stat-label {
          color: #909399;
          font-size: 14px;
          margin-right: 8px;
        }

        .stat-value {
          color: #303133;
          font-weight: 500;

          .never-expires {
            color: #67c23a;
            font-weight: 600;
          }
        }
      }
    }

    .share-settings {
      margin-bottom: 20px;
    }

    .share-actions {
      display: flex;
      gap: 12px;
      justify-content: flex-end;
    }
  }

  .share-form {
    .form-tip {
      display: block;
      margin-top: 4px;
      font-size: 12px;
      color: #909399;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>

